/** 
 * DefaultMatchSeriesParsable.java Created by iweerarathna on Aug 30, 2011.
 * 
 * Copyright (c) 2011 Virtusa Corporation. All Rights Reserved.<br><br>. 
 * 
 */
package org.uim.cricket.analyzer.parsers.match.impl;

import java.util.HashMap;

import org.uim.cricket.analyzer.parsers.Plogger;
import org.uim.cricket.analyzer.parsers.match.MatchSeriesParsable;
import org.uim.cricket.analyzer.parsers.misc.URLIDParsable;
import org.uim.cricket.entities.match.CricketMatch;
import org.uim.cricket.entities.match.SeriesPlayed;
import org.uim.cricket.util.HTMLStringUtils;

/**
 * TODO Class description goes here.
 * @version 
 * @author iweerarathna
 */
public class DefaultMatchSeriesParser implements MatchSeriesParsable {

    private URLIDParsable urlIdParser = null;
    
    public DefaultMatchSeriesParser() {
        
    }
    
    public DefaultMatchSeriesParser(URLIDParsable theUrlIdParser) {
        this.urlIdParser = theUrlIdParser;
    }
    
    @Override
    public SeriesPlayed parseSeries(String source, CricketMatch match) {
        if (source == null) return null;
        
        SeriesPlayed series = new SeriesPlayed();
        int pos = source.indexOf('<');
        int epos = source.indexOf('>', pos + 1);
        String tag = source.substring(pos, epos + 1);
        
        HashMap<String, String> attribs = HTMLStringUtils.getHTMLAttributes(tag);
        if (this.urlIdParser != null) {
            series.setId(this.urlIdParser.parseUrlID(attribs.get("href")));
        } else {
            series.setId(attribs.get("href"));
        }
        series.setSeriesLink(attribs.get("href"));
        
        pos = source.indexOf("</a>");
        if (pos < 0) {
            series.setName(HTMLStringUtils.cleanHTMLTags(source));
        } else {
            series.setName(source.substring(epos + 1, pos));
            String smatch = source.substring(pos + 4).trim();
            if (smatch.startsWith("-")) {
                series.setMatch(smatch.substring(1).trim());
            } else {
                series.setMatch(smatch);
            }
        }

        Plogger.info("   series name: " + series.getName());
        Plogger.info("   series match: " + series.getMatch());
        
        return series;
    }

    public void setUrlIdParser(URLIDParsable urlIdParser) {
        this.urlIdParser = urlIdParser;
    }
    
    public URLIDParsable getUrlIdParser() {
        return urlIdParser;
    }
}
